<!-- FILE:templates/apps/stats.html -->
<!--Body content-->
<div id="content" class="clearfix">
    <div class="contentwrapper"><!--Content wrapper-->
        <!-- Build page from here: -->
        <div class="row-fluid">
          <div class="span12">
            <div class="page-header">
                <h1>App Statistics for {{ appid }}</h1>
            </div><!--close header-->
              <div class="row-fluid">
              <div class="row-fluid">
                <div id="total-requests" style="margin-right:auto; margin-left:auto;">
                </div><!-- close marginright -->
                <div style="margin-right:auto; margin-left:auto;">
                  <p>Requests per second:</p>
                </div><!-- close marginright -->
                <div class="offset1 span8">
                  <div class="graph-container">
                    <div class="graph" id="requests-per-second-flot"></div>
		  </div><!-- close request per sec container -->
                </div><!-- close offset -->
              </div><!-- close row fluid-->
              <div class="row-fluid">
                <div style="margin-right:auto; margin-left:auto;">
                  <p>Kind statistics: <a id='groomer' href="#" class="btn btn-primary btn-large">Update</a></p>
                </div><!-- close marginright -->
                <div class="offset1 span8">
                  <div class="flot-container">
                    <div id="kind-flot" class="flot-placeholder"></div>
		  </div><!-- close kind container-->
                </div><!-- close offset -->
              </div><!-- close row fluid-->
              <div class="row-fluid">
                <div style="margin-right:auto; margin-left:auto;">
                  <p>Instances hosting this app:<span
                          id="num-instances"></span></p>
                </div><!-- close marginright -->
                <div class="offset1 span8">
                  <table class="table">
                    <thead>
                      <tr>
                        <td>Host</td>
                        <td>Port</td>
                        <td>Language</td>
                      </tr>
                    </thead>
                    <tbody id="instance-info-table">
                    </tbody>
                  </table>
                </div><!-- close offset -->
              </div><!-- close row fluid-->
        </div><!--close span6 -->
        </div> <!-- end row fluid -->
    </div> <!-- end content wrapper -->
</div> <!--end content-->

<script>
// Calls the Groomer if the user clicks on the 'Update' button.
$('#groomer').click(function() {
  $.ajax({
    url: "/groomer"
  }).done(
  function(response) {
    console.log(response);
    update_stats_info();
  });
});

//Plots JSON data on a line graph
window.onload = function() {
  update_request_info();
  update_stats_info();
  update_instance_info();

  setInterval(
    function() {
      update_request_info();
      update_stats_info();
      update_instance_info();
    }, 20000);
};
/**
 * Updates the instance info for the application.
 */
function update_instance_info() {
    $.ajax({
        url: "/apps/stats/instances?appid={{ appid }}"
    }).done(
            function(json_data){
                var instance_info = JSON.parse(json_data);
                var instance_rows = "";
                for (var index = 0; index < instance_info.length; index++) {
                    var table_col = '<td style="text-align:left">';
                    var instance_host = table_col +
                            instance_info[index]['host'] + '</td>';
                    var instance_port = table_col +
                            instance_info[index]['port'] + '</td>';
                    var instance_lang = table_col +
                            instance_info[index]['language'] + '</td>';
                    instance_rows += "<tr>" + instance_host + instance_port +
                            instance_lang + "</tr>";
                }
                $("#num-instances").html(instance_info.length);
                $("#instance-info-table").html(instance_rows)
            }
    )
}

/**
 * Updates the graph that tells users how many requests per second reach their
 * application. If no data is available, then we display a message to the user
 * instead.
 */
function update_request_info() {
  $.ajax({
    url: "/apps/stats/requests?appid={{ appid }}"
  }).done(
  function(json_data) {
    var req_info = JSON.parse(json_data);
    var thetuples = [];
    for (var index = 0; index < req_info.length; index++) {
      var x = req_info[index]['timestamp'] * 1000;
      var y = req_info[index]['avg_request_rate'];
      thetuples.push({ timestamp: x, avg_request_rate: y });
    }

    if (thetuples.length == 0) {
      $('#requests-per-second-flot').text('No request data is currently ' +
        'available. This data is generated once every minute, so ' +
        'please wait and it should be updated shortly.');
    } else {
      $('#requests-per-second-flot').text('');
      new Morris.Line({
        element: 'requests-per-second-flot',
        data: thetuples,
        xkey: 'timestamp',
        ykeys: ['avg_request_rate'],
        labels: ['Average Number of Requests per Second']
      });
      var last_request_info = req_info[0];
      $('#total-requests').html("<p>Total Requests Seen: " +
              last_request_info['num_of_requests'] + "</p>");
    }
  });
}


/**
 * Updates the pie chart that tells users what Kinds their application has
 * stored in the Datastore, as well as the percentage that each Kind is storing
 * compared to the other Kinds.
 */
function update_stats_info() {
  $.ajax({
    url: "/apps/stats/datastore?appid={{ appid }}"
  }).done(
    function(json_data) {
      var stats_info = JSON.parse(json_data);
      var newest_info = stats_info[stats_info.length-1];
      var newest_timestamp = null;
      for (var timestamp in newest_info) {
        newest_timestamp = timestamp;
      }

      var data = [];
      for (var index=0; index < stats_info.length; index++) {
        entity_info = stats_info[index];
        var this_timestamp = null;
        for (var timestamp in entity_info) {
          this_timestamp = timestamp;
        }
        if (this_timestamp == newest_timestamp) {
          var entity_stats = entity_info[this_timestamp];
          for (var entity_name in entity_stats) {
            var entity_count = entity_stats[entity_name]["count"];
            var entity_size = entity_stats[entity_name]["bytes"];
            data.push({ label: entity_name + " (" + entity_count + " items, " +
              entity_size + " bytes)", data: [[1, entity_size]] });
          }
        }
      }

      if (data.length == 0) {
        $('#kind-flot').text("No Kind data is currently available. " +
          "This data updates every day by default, or you can click " +
          "the 'Update' button above to manually generate this data.");
      } else {
        // Give the pie chart area a height so it will be displayed.
        $('#kind-flot').text('').css('height','400px');
        $.plot('#kind-flot', data, {
          series: {
            pie: {
              show: true
            }
          },
          grid: {
		    hoverable: true
			},
	      tooltip: true,
          tooltipOpts: {
				content: "%s",
				shifts: {
					x: 20,
					y: 0
				},
		  defaultTheme: true
			},
          legend: {
            show: true
          }
        });
      }
    });
}

</script>
</div>
